<!-- 消息提示组件 - 提供全局的消息通知和提示功能 -->
<template>
  <Transition name="toast-fade">
    <div 
      v-if="visible" 
      class="message-toast"
      :class="['message-toast--' + type]"
      :style="customStyle"
    >
      <span class="message-toast__content">{{ message }}</span>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'

// 定义组件的 Props 接口
interface Props {
  message: string
  type?: 'success' | 'warning' | 'error' | 'info'
  duration?: number
  showClose?: boolean
  customStyle?: Record<string, string>
  onClose?: () => void
}

// 组件 Props
const props = withDefaults(defineProps<Props>(), {
  type: 'info',
  duration: 3000,
  showClose: false,
  customStyle: () => ({})
})

// 组件 Emits
const emit = defineEmits<{
  close: []
}>()

// 组件状态
const visible = ref(false)
let timer: number | null = null

// 控制显示的方法
const show = () => {
  visible.value = true
}

// 控制隐藏的方法
const hide = () => {
  visible.value = false
  // 动画结束后触发关闭回调
  setTimeout(() => {
    emit('close')
    props.onClose?.()
  }, 300)
}

// 监听 visible 变化，处理自动关闭
watch(() => visible.value, (newVal) => {
  if (newVal) {
    startTimer()
  }
})

// 启动定时器
const startTimer = () => {
  if (timer) {
    clearTimeout(timer)
  }
  if (props.duration > 0) {
    timer = window.setTimeout(() => {
      hide()
    }, props.duration)
  }
}

// 清理定时器
const clearTimer = () => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}

// 组件挂载和卸载时的生命周期处理
onMounted(() => {
  show()
})

onUnmounted(() => {
  clearTimer()
})

// 暴露方法给父组件
defineExpose({
  show,
  hide
})
</script>

<style scoped>
/* 基础样式 */
.message-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 12px 20px;
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  z-index: 9999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 80%;
  word-break: break-word;
  text-align: center;
}

/* 不同类型的样式 */
.message-toast--success {
  background-color: #67c23a;
}

.message-toast--warning {
  background-color: #e6a23c;
}

.message-toast--error {
  background-color: #f56c6c;
}

.message-toast--info {
  background-color: #909399;
}

/* 动画效果 */
.toast-fade-enter-active,
.toast-fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.toast-fade-enter-from {
  opacity: 0;
  transform: translate(-50%, -40%);
}

.toast-fade-leave-to {
  opacity: 0;
  transform: translate(-50%, -60%);
}

/* 内容样式 */
.message-toast__content {
  display: inline-block;
  line-height: 1.4;
}
</style>